package ldk.app.kotlinweibo.apis

import com.google.gson.Gson
import ldk.app.kotlinweibo.apis.beans.BaseResponse
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.internal.http.RealInterceptorChain
import org.junit.Test

import org.junit.Assert.*
import org.junit.Before
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner

/**
 * Created by ke on 17-6-28.
 */
@RunWith(PowerMockRunner::class)
@PrepareForTest(Response::class, ResponseBody::class, RealInterceptorChain::class)
class APIInterceptorTest {

    private lateinit var interceptor: APIInterceptor

    @Before
    fun setUp(){
        interceptor = APIInterceptor(Gson())
    }

    @Test
    fun intercept() {
        val responseBody = PowerMockito.mock(ResponseBody::class.java)
        val response = PowerMockito.mock(Response::class.java)
        PowerMockito.`when`(response.body()).thenReturn(responseBody)
        val chain = PowerMockito.mock(RealInterceptorChain::class.java)
        PowerMockito.`when`(chain.proceed(Mockito.any())).thenReturn(response)
        val emptyResponse = "{}"
        val errorResponse = "{\"request\":\"/statuses/home_timeline.json\",\"error_code\":\"20502\",\"error\":\"Need you follow uid.\"}"
        PowerMockito.`when`(responseBody.string()).thenReturn(emptyResponse)
        assertEquals(response, interceptor.intercept(chain))
        PowerMockito.`when`(responseBody.string()).thenReturn(errorResponse)
        try {
            interceptor.intercept(chain)
            throw IllegalStateException("Cannt be here")
        }catch (e: BaseResponse){
            assertEquals("20502", e.error_code)
        }
    }

}